﻿using Microsoft.Win32;
using PMSystem.DataAccess;
using PMSystem.DataAccess.DataRepository;
using PMSytem.Windows.App;
using PMSytem.Windows.App.Pages;
using PMSytem.Windows.App.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PMSytem.Windows.Tests
{
    public class Images
    {
        public ImageSource Image;
        public byte[] ImageByte;
    }

    public partial class RecordWindow : ToolWindow
    {
        private us_Photos controlPhotos;
        private List<Images> imageList;
        private List<ImageSource> imageListPrev;

        public RecordWindow()
        {
            InitializeComponent();

            DataContext = new RecordImageSource();
            controlPhotos = new us_Photos();
            imageList = new List<Images>();
            imageListPrev = new List<ImageSource>();
        }

        private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            //ColorChooser colorChooser = new ColorChooser();
            //colorChooser.ToolWindowState = ToolWindowState.Maximized;
            //colorChooser.StartPosition = ToolWindowStartPosition.CenterParent;
            //colorChooser.Parent = this.Parent;
            //colorChooser.Show();

            try
            {
                using (var repo = new RecordItemRepository())
                {
                    var record = new RecordItem()
                    {
                        RecordNumber = txtRecordNo.Text,
                        RackNumber = txtRackNo.Text,
                        TrayNumber=txtTrayNo.Text,
                        Author = txtAuthor.Text,
                        Title= txtTitle.Text,
                        Description = txtDescription.Text,
                        CreatedBy = LoginUser.CurrentUser.UserName,
                        CreatedDate = DateTime.Now
                    };

                    repo.InsertOrUpdate(record);
                    repo.Save();
                                      
                    var newrecordid = record.RecordId;
                    if (newrecordid > 0)
                    {
                        AuditManager.AddAuditRecord(AuditEntity.CreateRecord, "create a new record item( record id:" + newrecordid + ")"); 
                        SavePhotos(newrecordid);

                        MessageBox.Show("Successfully added new record.", "Add Record Status",
                                MessageBoxButton.OK,
                                MessageBoxImage.Information,
                                MessageBoxResult.OK,
                                null);
                        Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        private void SavePhotos(int recordid)
        {
            try
            {
                if (imageList != null && imageList.Count > 0)
                {
                    using (var repo = new RecordItemImageRepository())
                    {
                        foreach (var image in imageList)
                        {
                            try
                            {
                                var recordimage = new RecordItemImage()
                                {
                                    RecordId = recordid,
                                    Image = image.ImageByte,
                                    ImageBinary = image.ImageByte
                                };
                                repo.InsertOrUpdate(recordimage);
                                repo.Save();
                            }
                            catch (Exception ex)
                            {
                                var errr = ex.Message;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "Select a picture";
            op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";

            if (op.ShowDialog() == true)
            {
                //ImageSource imageSource = new BitmapImage(new Uri(op.FileName));
                ////image.Source = imageSource;

                txtflepath.Text = op.FileName;

                //var imgbytes = File.ReadAllBytes(op.FileName);
                //ImageSource img = ByteToImage(imgbytes);

                //// thumbNail.Source = ByteImageConverter.ByteToImage(imgbytes);

                //var imageobj = new Images();
                //imageobj.ImageByte = imgbytes;
                //imageobj.Image = img;
                //imageList.Add(imageobj);

                ////var temp =  new List<ImageSource>();
                ////ImageSource img = ByteToImage(imgbytes);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);

                ////imageList.AddRange(imageobj);
                //imageListPrev.Add(img);
            }
        }

        public static ImageSource ByteToImage(byte[] imageData)
        {
            BitmapImage biImg = new BitmapImage();
            MemoryStream ms = new MemoryStream(imageData);
            biImg.BeginInit();
            biImg.StreamSource = ms;
            biImg.EndInit();

            ImageSource imgSrc = biImg as ImageSource;

            return imgSrc;
        }

        private void btnUpoad_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtflepath.Text))
                return;
                
            var filename = txtflepath.Text;
            var imgbytes = File.ReadAllBytes(filename);
            ImageSource img = ByteToImage(imgbytes);

            var imageobj = new Images();
            imageobj.ImageByte = imgbytes;
            imageobj.Image = img;
            imageList.Add(imageobj);
            imageListPrev.Add(img);

            txtflepath.Text = "";
            (this.photos.DataContext as RecordImageSource).PhotoList = null;
            this.photos.DataContext = new RecordImageSource() { PhotoList = imageListPrev };
        }

        private void Clear()
        {
            txtRecordNo.Text = txtRackNo.Text = txtTrayNo.Text = txtDescription.Text = txtTitle.Text = txtAuthor.Text = "";
            (this.photos.DataContext as RecordImageSource).PhotoList = null;
        }
    }
}